#!/bin/bash

if [[ "${BUILDER_TARGET}" =~ ^doc.* ]]; then
  exit 0
fi

SRCDIR="${BUILDER_TMP}/${BUILDER_VERSION}/${BUILDER_TARGET}"
DESTDIR="built_pkgs/"

mkdir -p ${DESTDIR}

# We need the GNU version of tar for --transform
[ -z "$tar" ] && tar=`which gtar tar | grep '^/' | head -1`
if ! $tar --version | grep -q GNU; then
    echo "ERROR: could not find GNU tar (as gtar or tar)"
    echo "On macOS: brew install gnu-tar"
    exit 1
fi

# pdns (auth) is handled seperately, it needs a special find condition which is hard to do with
# vars, as we don't want the asterisks to expand prematurely. So repeat the body of the loop below
# with a find condition for pdns to exclude accidentally matching pdns-recursor*.
for prog in pdns-recursor dnsdist; do
  if [ $(find ${SRCDIR}/dist -name "${prog}*" 2>/dev/null | wc -l) -ne 0 ]; then
    extension="tar.bz2"
    if [ "$prog" = "dnsdist" ]; then
      extension="tar.xz"
    fi
    dst=${DESTDIR}/${prog}/${BUILDER_VERSION}
    mkdir -p ${dst}
    cp ${BUILDER_TMP}/${BUILDER_VERSION}/sdist/${prog}*.${extension} ${dst}
    tardirname=${prog}-${BUILDER_VERSION}-${BUILDER_TARGET}
    "$tar" -cjf ${dst}/${tardirname}.tar.bz2 --transform="s,.*/,${tardirname}/,g"  $(find ${SRCDIR} -type f)
  fi
done
prog=pdns
if [ $(find ${SRCDIR}/dist -name 'pdns*' -a ! -name 'pdns-recursor*' 2>/dev/null | wc -l) -ne 0 ]; then
  dst=${DESTDIR}/${prog}/${BUILDER_VERSION}
  mkdir -p ${dst}
  cp ${BUILDER_TMP}/${BUILDER_VERSION}/sdist/${prog}*.tar.bz2 ${dst}
  tardirname=${prog}-${BUILDER_VERSION}-${BUILDER_TARGET}
  "$tar" -cjf ${dst}/${tardirname}.tar.bz2 --transform="s,.*/,${tardirname}/,g"  $(find ${SRCDIR} -type f)
fi
